package com.android.example.record;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.android.example.record.activity.SelectLocActivity;
import com.android.example.record.adapter.ViewPager2Adapter;
import com.android.example.record.bean.HistoryData;
import com.android.example.record.bean.ImageBean;
import com.android.example.record.bean.RecordBean;
import com.android.example.record.databinding.ActivityMainBinding;
import com.android.example.record.fragment.SettingFragment;
import com.android.example.record.service.LocationService;
import com.android.example.record.service.ServiceUtils;
import com.android.example.record.utils.ImageUtil;
import com.android.example.record.utils.MediaUtils;
import com.android.example.record.utils.SharedPreferencesUtil;
import com.android.example.record.utils.Utils;
import com.android.example.record.viewmodel.SirenViewModel;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.bumptech.glide.Glide;
import com.google.android.material.circularreveal.CircularRevealRelativeLayout;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements
        SurfaceHolder.Callback,
        MediaRecorder.OnErrorListener,
        SensorEventListener {

    private static final int SAVE_DATA = 0;
    private static final int SAVE_RECORD = 1;
    public static int orientation = 0;
    public SensorManager sensorManager;
    public Sensor sensor;
    public int sensorRotation = 0;
    String recordName;
    ImageBean imageFrontBean;
    ImageBean imageOverallBean;
    ImageBean imageRearBean;
    ImageBean imageInsideBean;
    double latitude;
    double longitude;
    double selectLatitude;
    double selectLongitude;
    Toast toast;
    Intent intent;
    private ActivityMainBinding binding;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private MediaRecorder mediaRecorder;
    private int useWidth;
    private int useHeight;
    private LocationService locationService;
    private final BDAbstractLocationListener bdListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(final BDLocation location) {

            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                int tag = 1;
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < 1; i++) {
                        Poi poi = location.getPoiList().get(i);
                        String add = poi.getName() + "\n" + poi.getAddr();
                        logMsg(add, tag);
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }

                binding.selectAddTextView.setOnClickListener(v -> new Thread(() -> goSelect(location)).start());
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }
    };
    private List<Fragment> settingFragment;
    private MediaUtils mediaUtils;
    private String save_record_path;
    private boolean isRecording;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        // Hide the status bar.
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        System.out.println("MainActivity执行了onCreate");
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();

        binding.recordButton.setOnClickListener(this::switchRecord);
        binding.addEditText.setOnClickListener(this::editAddress);
        binding.getAddTextView.setOnClickListener(this::getAddress);
        binding.imageFront.setOnClickListener(v ->
                imageFrontBean.setSaveName(takePhoto(binding.imageFront, getPhotoName())));
        binding.imageOverall.setOnClickListener(v ->
                imageOverallBean.setSaveName(takePhoto(binding.imageOverall, getPhotoName())));
        binding.imageRear.setOnClickListener(v ->
                imageRearBean.setSaveName(takePhoto(binding.imageRear, getPhotoName())));
        binding.imageInside.setOnClickListener(v ->
                imageInsideBean.setSaveName(takePhoto(binding.imageInside, getPhotoName())));
        binding.done.setOnClickListener(v -> confirmAlertDialog("提示", "是否要保存信息", SAVE_DATA));

        mediaUtils = new MediaUtils(this);
        save_record_path = Utils.getRecordPath(this);
        isRecording = false;

        imageFrontBean = new ImageBean(binding.imageFront);
        imageOverallBean = new ImageBean(binding.imageOverall);
        imageRearBean = new ImageBean(binding.imageRear);
        imageInsideBean = new ImageBean(binding.imageInside);

        startSurfaceView();

        SirenViewModel sirenViewModel = new ViewModelProvider(this).get(SirenViewModel.class);
        sirenViewModel.getSiren().observe(this, s -> binding.sirenTextView.setText(s));

        sensorManager = (SensorManager) MainActivity.this.getSystemService(AppCompatActivity.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    public void startSurfaceView() {    /* 初始化启动 SurfaceView */
        surfaceHolder = binding.surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        setSurfaceViewParams(3, 4);
    }

    public void initCamera() {  // 初始化 Camera
        if (camera != null) {
            releaseCamera();
        }
        camera = Camera.open(0);

        if (camera != null) {
            try {
                camera.setPreviewDisplay(surfaceHolder);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Camera.Parameters parameters = camera.getParameters();
            parameters.setRecordingHint(true);

            parameters.setPictureFormat(ImageFormat.JPEG);
            parameters.set("jpeg-quality", 100);
            camera.setPreviewCallback((data, camera) -> {

            });

            camera.setParameters(parameters);
            camera.setParameters(parameters);
            mediaUtils.calculateCameraPreviewOrientation(this);

            //noinspection SuspiciousNameCombination
            mediaUtils.setPictureSize(camera, useHeight, useWidth);
            camera.setDisplayOrientation(orientation);
            int degree = mediaUtils.calculateCameraPreviewOrientation(this);
            camera.setDisplayOrientation(degree);

            camera.startPreview();
        }
    }

    /**
     * 拍照并保存图片
     *
     * @param imageView 按钮和图片预览
     * @param photoName 图片名
     * @return photoName
     */
    public String takePhoto(final AppCompatImageView imageView, String photoName) {
        // if (isRecording) {
        //     try {
        //         stopRecord();
        //     } catch (Exception e) {
        //         e.printStackTrace();
        //     }
        // }
        camera.takePicture(null, null, (data, camera) -> {
            // camera.autoFocus(null);
            mediaUtils.setImageBitmap(data, imageView);
            camera.stopPreview();
            camera.startPreview();
        });

        int id = imageView.getId();
        if (id == R.id.image_front) {
            imageFrontBean.setClock(binding.textClock.getText().toString());
        } else if (id == R.id.image_overall) {
            imageOverallBean.setClock(binding.textClock.getText().toString());
        } else if (id == R.id.image_rear) {
            imageRearBean.setClock(binding.textClock.getText().toString());
        } else if (id == R.id.image_inside) {
            imageInsideBean.setClock(binding.textClock.getText().toString());
        }
        return photoName;
    }

    public void releaseCamera() { // 释放 Camera
        if (camera != null) {
            surfaceHolder.removeCallback(this);
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.lock();
            camera.release();
            camera = null;
        }
    }

    /**
     * 显示请求字符串
     *
     * @param str 请求字符串
     */
    public void logMsg(final String str, final int tag) {
        try {
            new Thread(() -> binding.addEditText.post(() -> {
                if (tag == ServiceUtils.RECEIVE_TAG) {
                    if (TextUtils.isEmpty(str)) {
                        Utils.displayToast(MainActivity.this, "定位失败", toast);
                        return;
                    }

                    if (binding.getAddTextView.getText().toString().equals("重新\n定位")) {
                        binding.addEditText.setHintTextColor(Color.BLACK);
                        binding.addEditText.setTextSize(12);
                        binding.addEditText.setHint(str);
                        Utils.displayToast(MainActivity.this, "定位成功", toast);
                        locationService.stop();
                        return;
                    }

                    if (TextUtils.isEmpty(binding.addEditText.getText())) {
                        binding.addEditText.setHintTextColor(Color.GRAY);
                        binding.addEditText.setTextSize(18);
                        binding.addEditText.setHint("地址");
                        return;
                    }
                }

                if (tag == ServiceUtils.DIAGNOSTIC_TAG) {
                    Utils.displayToast(MainActivity.this, "获取定位失败", toast);
                }
            })).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void switchRecord(View v) {
        try {
            if (!isRecording) {
                startRecord();
            } else {
                stopRecord();
                Utils.displayToast(MainActivity.this, "结束录像", toast);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void editAddress(View v) {
        binding.addEditText.setHint("");
    }

    public void getAddress(View v) {
        binding.addEditText.setHint("");
        if (binding.getAddTextView.getText().toString().equals("重新\n定位")) {
            locationService.start();
        } else if (binding.getAddTextView.getText().toString().equals("开始\n定位")) {
            binding.getAddTextView.setText("重新\n定位");
        }
        binding.addEditText.setText("");
    }

    private void startRecord() throws Exception {
        initRecord();
        Glide.with(this).load(R.drawable.recording).into(binding.recordButton);
        binding.recordButton.setColorFilter(null);
    }

    private void initRecord() throws Exception { // 初始化 录像预览
        setSurfaceViewParams(9, 16);
        camera.unlock();
        mediaRecorder = new MediaRecorder();
        recordName = getRecordName();
        mediaRecorder.reset();
        if (camera != null) {
            mediaRecorder.setCamera(camera);
        }
        mediaRecorder.setOnErrorListener(this);

        mediaRecorder.setOrientationHint(90);
        mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setVideoSize(1280, 720);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mediaRecorder.setVideoEncodingBitRate(2 * 1024 * 1024);
        mediaRecorder.setOutputFile(getRecordFile(recordName));
        mediaRecorder.prepare();
        mediaRecorder.start();
        Utils.displayToast(MainActivity.this, "开始录像", toast);
        isRecording = true;
    }

    private void stopRecord() {
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setPreviewDisplay(null);
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }
        isRecording = false;
        Glide.with(this).load(R.drawable.record_ready).into(binding.recordButton);
        binding.recordButton.setColorFilter(Color.WHITE);
        setSurfaceViewParams(9, 12);
        confirmAlertDialog("提示", "是否保存录像", SAVE_RECORD);
    }

    private void initView() {
        String preferences_siren = SharedPreferencesUtil.getParam(this, SharedPreferencesUtil.SIREN, "");
        binding.sirenTextView.setText(preferences_siren);
        binding.recordButton.setColorFilter(Color.WHITE);

        int width = getResources().getDisplayMetrics().widthPixels;
        ViewGroup.LayoutParams layoutParams = binding.settingViewPager2.getLayoutParams();
        layoutParams.width = width / 2;
        binding.settingViewPager2.setLayoutParams(layoutParams);

        initFragment();

        ViewPager2Adapter settingViewPager2Adapter = new ViewPager2Adapter(this, settingFragment);
        binding.settingViewPager2.setAdapter(settingViewPager2Adapter);
        binding.addEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(binding.addEditText.getText())) {
                    binding.addEditText.setTextSize(18);
                    binding.addEditText.setHintTextColor(Color.GRAY);
                    binding.addEditText.setHint("地址");
                }
            }
        });
    }

    private void confirmAlertDialog(String title, String msg, int methodID) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                .setTitle(title)
                .setMessage(msg)
                .setCancelable(true)
                .setPositiveButton("确认", (dialog, which) -> {
                    switch (methodID) {
                        case SAVE_DATA:
                            try {
                                save_data();
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            break;
                        case SAVE_RECORD:
                            save_record();
                            break;
                        default:
                            break;
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    if (methodID == SAVE_RECORD) {
                        Utils.deleteFile(save_record_path + recordName);
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.GREEN);
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
    }

    private void save_data() throws ParseException {
        if (isEditTextStringTrimEmpty(binding.addEditText) &&
                (TextUtils.isEmpty(binding.addEditText.getHint()) || binding.addEditText.getHint().toString().equals("地址"))) {
            Utils.displayToast(MainActivity.this, "地址为空", toast, Gravity.CENTER);
            return;
        }

        if (isEditTextStringTrimEmpty(binding.numberEditText)) {
            Utils.displayToast(MainActivity.this, "车牌号为空", toast, Gravity.CENTER);
            return;
        }

        if (imageFrontBean.getSaveName().equals("") || imageOverallBean.getSaveName().equals("") ||
                imageRearBean.getSaveName().equals("") || imageInsideBean.getSaveName().equals("")) {
            Utils.displayToast(MainActivity.this, "照片不全", toast, Gravity.CENTER);
            return;
        }

        if (TextUtils.isEmpty(binding.sirenTextView.getText())) {
            Utils.displayToast(MainActivity.this, "请设置警号", toast, Gravity.CENTER);
            return;
        }

        HistoryData historyData = new HistoryData();

        String siren = binding.sirenTextView.getText().toString();
        String loc = binding.addEditText.getText().toString();
        loc = TextUtils.isEmpty(loc) ? binding.addEditText.getHint().toString() : loc;
        if (binding.getAddTextView.getText().toString().equals("开始\n定位")) {
            historyData.setLatitude(String.valueOf(selectLatitude));
            historyData.setLongitude(String.valueOf(selectLongitude));
        } else {
            historyData.setLatitude(String.valueOf(latitude));
            historyData.setLongitude(String.valueOf(longitude));
        }
        String[] add = loc.split("\n");
        historyData.setSiren(siren);
        historyData.setAddress(add[1]);
        historyData.setErailName(add[0]);
        historyData.setNumber(binding.numberEditText.getText().toString().trim());
        historyData.setColor(getResources().getStringArray(R.array.colors)[binding.colorSpinner.getSelectedItemPosition()]);
        historyData.setImg_front_uri(imageFrontBean.getSaveName());
        historyData.setImg_overall_uri(imageOverallBean.getSaveName());
        historyData.setImg_rear_uri(imageRearBean.getSaveName());
        historyData.setImg_inside_uri(imageInsideBean.getSaveName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd EEEE HH:mm:ss", Locale.getDefault());
        String full_time = format.format(new Date());
        String[] split_time = full_time.split(" ");

        String save_date = split_time[0];
        String save_week = split_time[1];
        String save_time = split_time[2];
        historyData.setSave_date(save_date);
        historyData.setSave_week(save_week);
        historyData.setSave_time(save_time);
        if (historyData.save()) {
            Utils.displayToast(MainActivity.this, "保存成功", toast, Gravity.CENTER);
            ImageUtil.savePhoto(this, imageFrontBean.getSaveName(),
                    ImageUtil.drawTextToRightBottom(this,
                            ImageUtil.drawTextToLeftTop(this, imageFrontBean.getBitmap(), imageFrontBean.getClock(), 14, Color.BLACK, 10, 10),
                            siren, 14, Color.BLACK, 10, 10));
            ImageUtil.savePhoto(this, imageOverallBean.getSaveName(),
                    ImageUtil.drawTextToRightBottom(this,
                            ImageUtil.drawTextToLeftTop(this, imageOverallBean.getBitmap(), imageOverallBean.getClock(), 14, Color.BLACK, 10, 10),
                            siren, 14, Color.BLACK, 10, 10));
            ImageUtil.savePhoto(this, imageRearBean.getSaveName(),
                    ImageUtil.drawTextToRightBottom(this,
                            ImageUtil.drawTextToLeftTop(this, imageRearBean.getBitmap(), imageRearBean.getClock(), 14, Color.BLACK, 10, 10),
                            siren, 14, Color.BLACK, 10, 10));
            ImageUtil.savePhoto(this, imageInsideBean.getSaveName(),
                    ImageUtil.drawTextToRightBottom(this,
                            ImageUtil.drawTextToLeftTop(this, imageInsideBean.getBitmap(), imageInsideBean.getClock(), 14, Color.BLACK, 10, 10),
                            siren, 14, Color.BLACK, 10, 10));
        } else {
            Utils.displayToast(MainActivity.this, "保存失败", toast, Gravity.CENTER);
        }
    }

    private void save_record() {
        if (isEditTextStringTrimEmpty(binding.numberEditText)
                || TextUtils.isEmpty(binding.sirenTextView.getText())) {
            Utils.deleteFile(save_record_path + recordName);
            Utils.displayToast(MainActivity.this, "车牌号或者警号为空", toast, Gravity.CENTER);
            return;
        }

        RecordBean recordBean = new RecordBean();
        recordBean.setNumber(binding.numberEditText.getText().toString().trim());
        recordBean.setSiren(binding.sirenTextView.getText().toString());
        recordBean.setRecord_name(recordName);
        if (recordBean.save()) {
            Utils.displayToast(MainActivity.this, "保存成功", toast);
        } else {
            Utils.deleteFile(save_record_path + recordName);
            Utils.displayToast(MainActivity.this, "保存失败", toast);
        }
    }

    /**
     * 判断 AppCompatEditText 是否为空或者只包含空格
     *
     * @param editText 编辑的文本
     * @return True 为空
     */
    private boolean isEditTextStringTrimEmpty(EditText editText) {
        Editable editable = editText.getText();
        return TextUtils.isEmpty(editable) || editable.toString().trim().equals("");
    }

    /**
     * 设置SurfaceVie宽高比 height = width * y / x
     *
     * @param x 宽度 width
     * @param y 高度 height
     */
    private void setSurfaceViewParams(int x, int y) {
        int width = getResources().getDisplayMetrics().widthPixels;
        CircularRevealRelativeLayout.LayoutParams layoutParams =
                (CircularRevealRelativeLayout.LayoutParams) binding.surfaceView.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = width * y / x;
        useWidth = width;
        useHeight = width * y / x;
        binding.surfaceView.setLayoutParams(layoutParams);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            int x = (int) event.values[0];
            int y = (int) event.values[1];
            int z = (int) event.values[2];
        }

        sensorRotation = MediaUtils.calculateSensorRotation(event.values[0], event.values[1]);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        initCamera();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        initCamera();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }


    public void goSelect(BDLocation location) {
        intent = new Intent(this, SelectLocActivity.class);
        Double lat = location.getLatitude();
        Double lng = location.getLongitude();
        intent.putExtra("latitude", lat);
        intent.putExtra("longitude", lng);
        startActivity(intent);
    }

    private void initFragment() {
        settingFragment = new ArrayList<>();
        settingFragment.add(new SettingFragment());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        locationService.stop();
        binding.getAddTextView.setText("开始\n定位");
        super.onNewIntent(intent);
        setIntent(intent);
        getNewIntent();
        String loc = intent.getStringExtra("loc");
        selectLatitude = intent.getDoubleExtra("lat", 0.0);
        selectLongitude = intent.getDoubleExtra("lng", 0.0);

        if ((!TextUtils.isEmpty(loc))) {
            binding.addEditText.setTextSize(12);
        }
        binding.addEditText.setText(loc);
    }

    @Override
    public void setIntent(Intent newIntent) {
        super.setIntent(newIntent);
    }

    private void getNewIntent() {
        intent = getIntent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initCamera();
        // -----------location config ------------
        locationService = ((LocationApplication) getApplication()).locationService;
        locationService.registerListener(bdListener);
        locationService.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        startSurfaceView();
        if (camera != null) {
            camera.startPreview();
        }
        System.out.println("MainActivity执行了onResume");
    }

    @Override
    protected void onPause() {
        System.out.println("MainActivity执行了onPause");
        super.onPause();
        if (camera != null) {
            releaseCamera();
        }
        Utils.deleteFile(save_record_path + recordName);
    }

    @Override
    protected void onStop() {
        locationService.unregisterListener(bdListener); //注销掉监听
        locationService.stop(); //停止定位服务
        sensorManager.unregisterListener(this, sensor);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        System.out.println("MainActivity执行了onDestroy");
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (binding.drawerLayout.isDrawerOpen(binding.settingViewPager2)) {
            binding.drawerLayout.closeDrawer(binding.settingViewPager2);
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Utils.deleteFile(save_record_path + recordName);
        return super.onKeyDown(keyCode, event);
    }

    @SuppressWarnings("SpellCheckingInspection")
    public String getPhotoName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        String name = format.format(new Date());
        try {
            return format.parse(name).getTime() / 1000 + ".jpg";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getRecordFile(String recordName) {
        return mediaUtils.save_record(recordName);
    }

    @SuppressWarnings("SpellCheckingInspection")
    public String getRecordName() {
        return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + ".mp4";
    }


    @Override
    public void onError(MediaRecorder mr, int what, int extra) {

    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println("MainActivity数据恢复");
        binding.numberEditText.setText(savedInstanceState.getString("Number"));
        binding.imageFront.setImageBitmap(savedInstanceState.getParcelable("ImageFront"));
        binding.imageOverall.setImageBitmap(savedInstanceState.getParcelable("ImageOverall"));
        binding.imageRear.setImageBitmap(savedInstanceState.getParcelable("ImageRear"));
        binding.imageInside.setImageBitmap(savedInstanceState.getParcelable("ImageInside"));
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Editable number = binding.numberEditText.getText();
        if (number != null) {
            outState.putString("Number", number.toString());
        }
        outState.putParcelable("ImageFront", imageFrontBean.getBitmap());
        outState.putParcelable("ImageOverall", imageOverallBean.getBitmap());
        outState.putParcelable("ImageRear", imageRearBean.getBitmap());
        outState.putParcelable("ImageInside", imageInsideBean.getBitmap());
        super.onSaveInstanceState(outState);
        System.out.println("MainActivity数据保存");
    }

    public void closeDrawer() {
        binding.drawerLayout.closeDrawer(binding.settingViewPager2);
    }
}
